package org.egrit.demo;

import org.egrit.CalculatedGrid;
import org.egrit.GridFunction;
import org.egrit.Grids;
import org.egrit.IGrid;
import org.egrit.IGridBounds;

/**
 * A basic example to introduce the {@linkplain GridFunction} and 
 * {@linkplain CalculatedGrid} classes. We create a grid where cell
 * values are column position (X ordinate) expressed in the range 0 to 1.
 * 
 * @author michael
 */
public class CalculatedGridDemo {
    
    private static final int GRID_WIDTH = 5;
    private static final int GRID_HEIGHT = 5;
    
    private static final int OUTSIDE_VALUE = -1;
    
    public static void main(String[] args) {
        
        /*
         * GridFunction is an interface with a single method which
         * will be called by the associated grid when cell values
         * are queried.
         */
        GridFunction myFunction = new GridFunction() {

            @Override
            public Number apply(IGrid grid, int gridX, int gridY) {
                /*
                 * We don't really need to query the grid's min X
                 * ordinate here since we know it will be 0, but we
                 * do so to illustrate general use.
                 */
                IGridBounds bounds = grid.getGridBounds();
                return (double) (gridX - bounds.getMinGridX()) / (bounds.getWidth() - 1);
            }
        };

        /*
         * Now we create a grid which will use the above function.
         */
        IGrid myGrid = Grids.createCalculated(
                GRID_WIDTH, GRID_HEIGHT, myFunction, OUTSIDE_VALUE);

        /*
         * Print the grid values to the console. Once again we are
         * using the grid bounds to illustrate proper care about the
         * min X and Y ordinates as would be used in a general case.
         * 
         * We could also have used an IGridIterator to return the
         * sequence of grid cell positions instead of the for-loops.
         */
        final IGridBounds bounds = myGrid.getGridBounds();
        
        System.out.println("Grid values:");
        
        for (int y = bounds.getMinGridY(), iy = 0; iy < bounds.getHeight(); y++, iy++) {
            for (int x = bounds.getMinGridX(), ix = 0; ix < bounds.getWidth(); x++, ix++) {
                System.out.printf(" %.2f", myGrid.getGridValue(x, y));
            }
            System.out.println();
        }
    }
}
